<template>
  <div class="student-select">
    <el-card class="search-card">
      <template #header>
        <div class="card-header">
          <span>学生信息查询</span>
          <el-button type="primary" @click="showAdvancedSearch = !showAdvancedSearch">
            {{ showAdvancedSearch ? '收起筛选' : '展开筛选' }}
            <el-icon>
              <ArrowUp v-if="showAdvancedSearch" />
              <ArrowDown v-else />
            </el-icon>
          </el-button>
        </div>
      </template>
      
      <el-form 
        :model="searchForm" 
        ref="searchFormRef" 
        label-width="80px"
        class="search-form"
        :inline="!showAdvancedSearch"
      >
        <el-form-item label="姓名">
          <el-input 
            v-model="searchForm.name" 
            placeholder="请输入姓名"
            clearable
          />
        </el-form-item>
        
        <el-form-item label="地址">
          <el-input 
            v-model="searchForm.address" 
            placeholder="请输入地址"
            clearable
          />
        </el-form-item>
        
        <el-form-item v-show="showAdvancedSearch" label="出生日期">
          <el-date-picker
            v-model="searchForm.dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="YYYY-MM-DD"
            style="width: 100%"
          />
        </el-form-item>
        
        <el-form-item>
          <el-button type="primary" @click="onSearch" :icon="Search">
            查询
          </el-button>
          <el-button @click="onReset" :icon="Refresh">
            重置
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <el-card class="result-card">
      <template #header>
        <div class="card-header">
          <span>查询结果</span>
          <div class="actions">
            <el-button type="primary" @click="showAddDialog" :icon="Plus">新增学生</el-button>
            <el-button type="danger" @click="handleBatchDelete" :disabled="selectedStudents.length === 0" :icon="Delete">
              批量删除 ({{ selectedStudents.length }})
            </el-button>
            <el-button type="primary" @click="refreshData" :icon="Refresh">刷新</el-button>
          </div>
        </div>
      </template>
      
      <el-table 
        :data="displayStudents" 
        border 
        style="width: 100%"
        v-loading="loading"
        element-loading-text="数据加载中..."
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column prop="id" label="ID" width="80" sortable />
        <el-table-column prop="name" label="姓名" width="120" />
        <el-table-column prop="date" label="出生日期" width="150" />
        <el-table-column prop="address" label="地址" />
        <el-table-column label="操作" width="200">
          <template #default="scope">
            <el-button size="small" type="primary" @click="handleEdit(scope.row)">
              编辑
            </el-button>
            <el-button size="small" type="danger" @click="handleDelete(scope.row)">
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <div class="pagination-container">
        <el-pagination 
          background 
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          :current-page="currentPage"
          :page-size="pageSize"
          :page-sizes="[5, 10, 20, 50]"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
    
    <!-- 编辑对话框 -->
    <el-dialog v-model="dialogVisible" title="编辑学生信息" width="500px">
      <el-form :model="editForm" :rules="editRules" ref="editFormRef" label-width="80px">
        <el-form-item label="姓名" prop="name">
          <el-input v-model="editForm.name" />
        </el-form-item>
        <el-form-item label="出生日期" prop="date">
          <el-date-picker 
            v-model="editForm.date" 
            type="date" 
            value-format="YYYY-MM-DD"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="地址" prop="address">
          <el-input v-model="editForm.address" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="confirmEdit">确定</el-button>
        </span>
      </template>
    </el-dialog>
    
    <!-- 新增学生对话框 -->
    <el-dialog v-model="addDialogVisible" title="新增学生信息" width="500px">
      <el-form :model="addForm" :rules="addRules" ref="addFormRef" label-width="80px">
        <el-form-item label="姓名" prop="name">
          <el-input v-model="addForm.name" placeholder="请输入学生姓名" />
        </el-form-item>
        <el-form-item label="出生日期" prop="date">
          <el-date-picker 
            v-model="addForm.date" 
            type="date" 
            value-format="YYYY-MM-DD"
            placeholder="请选择出生日期"
            style="width: 100%"
          />
        </el-form-item>
        <el-form-item label="地址" prop="address">
          <el-input v-model="addForm.address" placeholder="请输入家庭地址" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="addDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="confirmAdd">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
import { ref, reactive, computed, onMounted } from 'vue'
import type { FormInstance, FormRules } from 'element-plus'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search, Refresh, ArrowUp, ArrowDown, Delete, Plus } from '@element-plus/icons-vue'
import { useStudentStore } from '@/stores/student'

// 定义学生信息类型
interface Student {
  id: number
  date: string
  name: string
  address: string
}

const studentStore = useStudentStore()
const searchFormRef = ref<FormInstance>()
const editFormRef = ref<FormInstance>()
const addFormRef = ref<FormInstance>()

// 状态
const showAdvancedSearch = ref(false)
const loading = ref(false)
const dialogVisible = ref(false)
const addDialogVisible = ref(false)
const selectedStudents = ref<Student[]>([])

// 搜索表单
const searchForm = reactive({
  name: '',
  address: '',
  dateRange: []
})

// 编辑表单
const editForm = reactive({
  id: 0,
  name: '',
  date: '',
  address: ''
})

// 新增表单
const addForm = reactive({
  name: '',
  date: '',
  address: ''
})

const editRules = reactive<FormRules>({
  name: [
    { required: true, message: '请输入学生姓名', trigger: 'blur' }
  ],
  date: [
    { required: true, message: '请选择出生日期', trigger: 'change' }
  ],
  address: [
    { required: true, message: '请输入家庭地址', trigger: 'blur' }
  ]
})

const addRules = reactive<FormRules>({
  name: [
    { required: true, message: '请输入学生姓名', trigger: 'blur' }
  ],
  date: [
    { required: true, message: '请选择出生日期', trigger: 'change' }
  ],
  address: [
    { required: true, message: '请输入家庭地址', trigger: 'blur' }
  ]
})

// 分页相关
const currentPage = ref(1);
const pageSize = ref(10);
const total = ref(studentStore.students.length);

// 显示的学生数据
const displayStudents = computed(() => {
  // 实现搜索逻辑
  let filteredStudents = [...studentStore.students];
  
  // 按姓名搜索
  if (searchForm.name) {
    filteredStudents = filteredStudents.filter(student => 
      student.name.includes(searchForm.name)
    );
  }
  
  // 按地址搜索
  if (searchForm.address) {
    filteredStudents = filteredStudents.filter(student => 
      student.address.includes(searchForm.address)
    );
  }
  
  // 按日期范围搜索
  if (searchForm.dateRange && searchForm.dateRange.length === 2) {
    const [startDate, endDate] = searchForm.dateRange;
    filteredStudents = filteredStudents.filter(student => {
      const studentDate = new Date(student.date);
      return studentDate >= new Date(startDate) && studentDate <= new Date(endDate);
    });
  }
  
  // 分页处理
  const start = (currentPage.value - 1) * pageSize.value;
  const end = start + pageSize.value;
  return filteredStudents.slice(start, end);
});

// 当每页的条数发生变化的时候触发
const handleSizeChange = (val: number) => {
  pageSize.value = val
  currentPage.value = 1
}

// 当页码发生变化的时候触发
const handleCurrentChange = (val: number) => {
  currentPage.value = val
}

// 搜索功能
const onSearch = () => {
  loading.value = true;
  currentPage.value = 1; // 搜索时回到第一页
  
  // 更新总数
  let filteredStudents = [...studentStore.students];
  
  // 按姓名搜索
  if (searchForm.name) {
    filteredStudents = filteredStudents.filter(student => 
      student.name.includes(searchForm.name)
    );
  }
  
  // 按地址搜索
  if (searchForm.address) {
    filteredStudents = filteredStudents.filter(student => 
      student.address.includes(searchForm.address)
    );
  }
  
  // 按日期范围搜索
  if (searchForm.dateRange && searchForm.dateRange.length === 2) {
    const [startDate, endDate] = searchForm.dateRange;
    filteredStudents = filteredStudents.filter(student => {
      const studentDate = new Date(student.date);
      return studentDate >= new Date(startDate) && studentDate <= new Date(endDate);
    });
  }
  
  total.value = filteredStudents.length;
  
  // 模拟搜索延迟
  setTimeout(() => {
    ElMessage.success('查询成功');
    loading.value = false;
  }, 300);
};

// 重置搜索条件
const onReset = () => {
  searchForm.name = '';
  searchForm.address = '';
  searchForm.dateRange = [];
  currentPage.value = 1; // 重置时回到第一页
  ElMessage.info('已重置搜索条件');

  // 更新 total 为重置后的学生总数
  total.value = studentStore.students.length;
};

// 刷新数据
const refreshData = () => {
  loading.value = true
  // 模拟刷新延迟
  setTimeout(() => {
    ElMessage.success('数据刷新成功')
    loading.value = false
  }, 300)
}

// 编辑学生信息
const handleEdit = (row: Student) => {
  editForm.id = row.id
  editForm.name = row.name
  editForm.date = row.date
  editForm.address = row.address
  dialogVisible.value = true
}

// 确认编辑
const confirmEdit = async () => {
  if (!editFormRef.value) return
  
  await editFormRef.value.validate((valid) => {
    if (valid) {
      studentStore.editStudent(editForm.id, {
        name: editForm.name,
        date: editForm.date,
        address: editForm.address
      })
      ElMessage.success('编辑成功')
      dialogVisible.value = false
    }
  })
}

// 删除学生信息
const handleDelete = (row: Student) => {
  ElMessageBox.confirm(
    `确定要删除学生 ${row.name} 的信息吗？`,
    '确认删除',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
  .then(() => {
    studentStore.deleteStudent(row.id)
    ElMessage.success('删除成功')
  })
  .catch(() => {
    ElMessage.info('已取消删除')
  })
}

// 处理选择变化
const handleSelectionChange = (selection: Student[]) => {
  selectedStudents.value = selection
}

// 批量删除
const handleBatchDelete = () => {
  if (selectedStudents.value.length === 0) {
    ElMessage.warning('请至少选择一个学生')
    return
  }
  
  ElMessageBox.confirm(
    `确定要删除选中的 ${selectedStudents.value.length} 个学生信息吗？`,
    '确认删除',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  )
  .then(() => {
    // 执行批量删除
    selectedStudents.value.forEach(student => {
      studentStore.deleteStudent(student.id)
    })
    ElMessage.success('批量删除成功')
    selectedStudents.value = []
  })
  .catch(() => {
    ElMessage.info('已取消删除')
  })
}

// 显示新增对话框
const showAddDialog = () => {
  // 重置表单
  addForm.name = ''
  addForm.date = ''
  addForm.address = ''
  addDialogVisible.value = true
}

// 确认新增
const confirmAdd = async () => {
  if (!addFormRef.value) return
  
  await addFormRef.value.validate((valid) => {
    if (valid) {
      studentStore.addStudent({
        name: addForm.name,
        date: addForm.date,
        address: addForm.address
      })
      ElMessage.success('新增成功')
      addDialogVisible.value = false
      // 刷新当前页以显示新增的学生
      refreshData()
    }
  })
}

// 初始化数据
onMounted(() => {
  refreshData()
})
</script>

<style scoped>
.student-select {
  padding: 20px;
  height: calc(100vh - 130px);
  display: flex;
  flex-direction: column;
}

.search-card {
  margin-bottom: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.search-form {
  margin-bottom: 10px;
}

.result-card {
  margin-top: 20px;
  flex: 1;
  display: flex;
  flex-direction: column;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.result-card :deep(.el-card__header) {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  border-radius: 8px 8px 0 0;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

.edit-form {
  max-width: 500px;
  margin: 0 auto;
}

.edit-dialog .el-input {
  width: 300px;
}

/* 自定义样式 */
.student-select :deep(.el-table th) {
  background-color: #f5f7fa;
}

.student-select :deep(.el-table__row:hover) {
  background-color: #f0f9ff;
}

.student-select :deep(.el-table__row:hover td) {
  background-color: transparent;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .student-select {
    padding: 10px;
  }
  
  .card-header {
    flex-direction: column;
    gap: 10px;
    align-items: flex-start;
  }
  
  .actions {
    width: 100%;
    display: flex;
    justify-content: space-between;
  }
}
</style>